<template>
  <div class="script-manage-container">
    <!-- 加载中状态 -->
    <el-skeleton :loading="loading" animated>
      <template #template>
        <el-skeleton-item variant="h1" style="width: 40%" />
        <el-skeleton-item variant="text" style="margin-top: 20px" />
      </template>

      <template #default>
        <!-- 未注册发行商 -->
        <div v-if="!isPublisher" class="not-publisher">
          <el-empty description="您还不是发行商">
            <el-button type="primary" @click="handleRegisterPublisher">
              注册成为发行商
            </el-button>
          </el-empty>
        </div>

        <!-- 已注册发行商 - 显示剧本列表 -->
        <div v-else class="publisher-content">
          <div class="header">
            <h2>剧本管理</h2>
            <el-button type="primary" @click="handleAddScript">
              <el-icon><PlusIcon /></el-icon>
              新增剧本
            </el-button>
          </div>

          <!-- 剧本列表 -->
          <el-table :data="scriptList" border style="width: 100%" v-loading="tableLoading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="title" label="剧本名称" min-width="150" />
            <el-table-column prop="author" label="作者" width="120" />
            <el-table-column prop="price" label="价格" width="100">
              <template #default="{ row }">
                ¥{{ row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="sold" label="是否售出" width="100">
              <template #default="{ row }">
                <el-tag :type="row.sold ? 'success' : 'danger'">
                  {{ row.sold ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="publishDate" label="发布日期" width="120" />
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click="handleDetail(row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 空状态 -->
          <el-empty v-if="scriptList.length === 0 && !tableLoading" description="暂无剧本数据" />
        </div>
      </template>
    </el-skeleton>

    <!-- 添加剧本对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加剧本"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item label="剧本名称" prop="title">
          <el-input
            v-model="addForm.title"
            placeholder="请输入剧本名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-input
            v-model="addForm.author"
            placeholder="请输入作者名称"
            clearable
          />
        </el-form-item>

        <el-form-item label="分类" prop="categoryId">
          <el-select
            v-model="addForm.categoryId"
            placeholder="请选择剧本分类"
            style="width: 100%"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="addForm.price"
            :min="0"
            :precision="2"
            :step="1"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="剧本封面" prop="contentFile">
          <el-upload
            class="upload-demo"
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            list-type="picture-card"
            accept="image/*"
          >
            <el-icon><PlusIcon /></el-icon>
          </el-upload>
          <div class="upload-tip">建议上传5:7比例的图片</div>
        </el-form-item>

        <el-form-item label="剧本简介" prop="description">
          <el-input
            v-model="addForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入剧本简介"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleCancelAdd">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmitAdd">
          提交
        </el-button>
      </template>
    </el-dialog>

    <!-- 剧本详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="剧本详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="script-detail">
        <div v-if="currentScript" class="detail-content">
          <!-- 剧本封面和基本信息 -->
          <div class="detail-header">
            <div class="detail-cover">
              <img
                :src="`${BASE_IMAGE_URL}/${currentScript.contentFile}`"
                :alt="currentScript.title"
                @error="handleImageError"
              />
            </div>
            <div class="detail-basic-info">
              <h2 class="detail-title">{{ currentScript.title }}</h2>
              <div class="info-item">
                <span class="info-label">作者：</span>
                <span class="info-value">{{ currentScript.author }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">出版社：</span>
                <span class="info-value">{{ currentScript.publishName || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">出版日期：</span>
                <span class="info-value">{{ currentScript.publishDate || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">分类：</span>
                <span class="info-value">{{ getCategoryName(currentScript.categoryId) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">状态：</span>
                <el-tag :type="getStatusType(currentScript.status)">
                  {{ getStatusText(currentScript.status) }}
                </el-tag>
              </div>
              <div class="info-item">
                <span class="info-label">已售：</span>
                <span class="info-value">{{ currentScript.sold || 0 }} 份</span>
              </div>
              <div class="info-item">
                <span class="info-label">使用天数：</span>
                <span class="info-value">{{ currentScript.usageDays || '未设置' }} 天</span>
              </div>
              <div class="info-item price-item">
                <span class="info-label">价格：</span>
                <span class="price-value">¥{{ currentScript.price }}</span>
              </div>
            </div>
          </div>

          <!-- 剧本简介 -->
          <div class="detail-description">
            <h3 class="section-title">剧本简介</h3>
            <p class="description-text">{{ currentScript.description || '暂无简介' }}</p>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { getPublisherByUserIdAPI } from '@/api/publisher'
import { getScriptListAPI } from '@/api/script'
import { uploadScriptImageAPI, addScriptAPI } from '@/api/mall'
import { ElMessage, type FormInstance, type FormRules, type UploadUserFile, type UploadFile } from 'element-plus'
import { Plus as PlusIcon } from '@element-plus/icons-vue'
import type { Script } from '@/types/script'
import { type ScriptFormData } from '@/api/mall'
const BASE_IMAGE_URL = import.meta.env.VITE_API_BASE_URL
// 发行商信息类型
interface PublisherInfo {
  id: number
  name: string
  phone: string
  email: string
  status: number
  [key: string]: unknown
}

const router = useRouter()

const loading = ref(true)
const tableLoading = ref(false)
const isPublisher = ref(false)
const publisherInfo = ref<PublisherInfo | null>(null)
const scriptList = ref<Script[]>([])

// 详情对话框相关
const detailVisible = ref(false)
const currentScript = ref<Script | null>(null)

// 添加剧本对话框相关
const addDialogVisible = ref(false)
const submitLoading = ref(false)
const addFormRef = ref<FormInstance>()
const fileList = ref<UploadUserFile[]>([])
const uploadedFile = ref<File | null>(null)

// 添加剧本表单
const addForm = reactive<ScriptFormData>({
  title: '',
  author: '',
  categoryId: 0,
  publisherId: 0,
  price: 0,
  contentFile: '',
  description: '',
  status: 0,
  sold: 0
})

// 表单验证规则
const addFormRules: FormRules<ScriptFormData> = {
  title: [
    { required: true, message: '请输入剧本名称', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者名称', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择剧本分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  contentFile: [
    { required: true, message: '请上传剧本封面', trigger: 'change' }
  ]
}

// 分类列表
const categories = [
  { id: 1, name: '剧情类' },
  { id: 2, name: '喜剧类' },
  { id: 3, name: '悬疑类' },
  { id: 4, name: '历史类' },
  { id: 5, name: '科幻类' }
]

// 检查是否是发行商
const checkPublisher = async () => {
  loading.value = true
  try {
    const { data: res } = await getPublisherByUserIdAPI()
    console.log('发行商查询结果：', res)
    // 如果 res.data 不为 null，说明是发行商
    if (res.code === 1 && res.data !== null) {
      isPublisher.value = true
      publisherInfo.value = res.data
      // 如果是发行商，获取剧本列表
      await getScriptList()
    } else {
      isPublisher.value = false
    }
  } catch (error) {
    console.log('不是发行商或查询失败', error)
    isPublisher.value = false
  } finally {
    loading.value = false
  }
}

// 获取剧本列表
const getScriptList = async () => {
  tableLoading.value = true
  try {
    const { data: res } = await getScriptListAPI()
    console.log('剧本列表原始数据：', res)
    if (res.code === 1) {
      // 使用发行商ID过滤剧本
      const publisherId = publisherInfo.value?.id
      console.log('当前发行商ID：', publisherId, '类型：', typeof publisherId)

      if (publisherId) {
        // 先看看所有剧本的 publisherId
        console.log('所有剧本的publisherId：', res.data.map((s: Script) => ({
          id: s.id,
          title: s.title,
          publisherId: s.publisherId,
          publisherIdType: typeof s.publisherId
        })))

        // 尝试两种匹配方式（转换为字符串比较）
        const filtered = res.data.filter((script: Script) => {
          const match = String(script.publisherId) === String(publisherId)
          console.log(`剧本${script.id}的publisherId: ${script.publisherId}(${typeof script.publisherId}), 当前发行商: ${publisherId}(${typeof publisherId}), 匹配: ${match}`)
          return match
        })

        scriptList.value = filtered
        console.log('过滤后的剧本列表：', scriptList.value)

        // 如果过滤后为空，显示所有剧本（临时调试）
        if (filtered.length === 0) {
          console.warn('过滤后没有剧本，暂时显示所有剧本')
          scriptList.value = res.data
        }
      }
    } else {
      ElMessage.error(res.msg || '获取剧本列表失败')
    }
  } catch (error) {
    console.error('获取剧本列表失败', error)
    ElMessage.error('获取剧本列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 注册成为发行商
const handleRegisterPublisher = () => {
  router.push('/publisher/register')
}

// 新增剧本
const handleAddScript = () => {
  addDialogVisible.value = true
}

// 文件选择处理
const handleFileChange = (file: UploadFile) => {
  if (!file.raw) return

  // 验证文件大小
  const isLt5M = file.size! / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过5MB')
    fileList.value = []
    uploadedFile.value = null
    return
  }

  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    fileList.value = []
    uploadedFile.value = null
    return
  }

  uploadedFile.value = file.raw
  addForm.contentFile = 'pending'
  // 手动触发表单验证
  addFormRef.value?.validateField('contentFile')
}

// 文件移除处理
const handleFileRemove = () => {
  uploadedFile.value = null
  addForm.contentFile = ''
  addFormRef.value?.validateField('contentFile')
}

// 重置表单
const resetAddForm = () => {
  addFormRef.value?.resetFields()
  fileList.value = []
  uploadedFile.value = null
  Object.assign(addForm, {
    title: '',
    author: '',
    categoryId: 0,
    publisherId: 0,
    price: 0,
    contentFile: '',
    description: '',
    status: 0,
    sold: 0
  })
}

// 取消添加
const handleCancelAdd = () => {
  addDialogVisible.value = false
  resetAddForm()
}

// 提交添加剧本
const handleSubmitAdd = async () => {
  if (!addFormRef.value) return

  try {
    // 验证表单
    await addFormRef.value.validate()

    submitLoading.value = true

    // 先上传图片
    if (!uploadedFile.value) {
      ElMessage.error('请上传剧本封面')
      submitLoading.value = false
      return
    }

    // 获取发行商ID
    const publisherId = publisherInfo.value?.id || 0
    if (!publisherId) {
      ElMessage.error('获取发行商信息失败')
      submitLoading.value = false
      return
    }

    // 上传图片
    const uploadRes = await uploadScriptImageAPI(uploadedFile.value, publisherId)
    if (uploadRes.data.code !== 1) {
      ElMessage.error(uploadRes.data.msg || '图片上传失败')
      submitLoading.value = false
      return
    }

    // 获取图片URL
    const imageUrl = uploadRes.data.data

    // 准备提交数据
    const submitData: ScriptFormData = {
      title: addForm.title,
      author: addForm.author,
      categoryId: addForm.categoryId,
      publisherId: publisherId,
      price: addForm.price,
      contentFile: imageUrl,
      description: addForm.description,
      status: 0, // 待审核
      sold: 0
    }

    console.log('提交的剧本数据：', submitData)

    // 提交剧本
    const res = await addScriptAPI(submitData)
    if (res.data.code !== 1) {
      ElMessage.error(res.data.msg || '添加剧本失败')
      submitLoading.value = false
      return
    }

    ElMessage.success('添加剧本成功，请等待审核')
    addDialogVisible.value = false
    resetAddForm()

    // 刷新列表
    await getScriptList()
  } catch (error) {
    console.error('添加剧本失败:', error)
    if (error !== false) { // 排除表单验证失败
      ElMessage.error('添加剧本失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 查看详情
const handleDetail = (row: Script) => {
  currentScript.value = row
  console.log('当前剧本：', currentScript.value)
  detailVisible.value = true
}

// 获取分类名称
const getCategoryName = (categoryId: number) => {
  const category = categories.find(cat => cat.id === categoryId)
  return category?.name || '未知分类'
}

// 图片加载失败处理
const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement
  target.src = 'https://lvyou-1332935562.cos.ap-nanjing.myqcloud.com/ceshi/IMG_1351.PNG'
}

// 获取状态类型
const getStatusType = (status: number) => {
  const typeMap: Record<number, string> = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: number) => {
  const textMap: Record<number, string> = {
    0: '待审核',
    1: '已发布',
    2: '审核中',
    3: '已下架'
  }
  return textMap[status] || '未知'
}

onMounted(() => {
  checkPublisher()
})
</script>

<style scoped>
.script-manage-container {
  padding: 20px;
}

.not-publisher {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.publisher-content {
  width: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

/* 上传组件样式 */
.upload-demo {
  display: flex;
  justify-content: flex-start;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 剧本详情样式 */
.script-detail {
  min-height: 400px;
}

.detail-content {
  padding: 10px 0;
}

.detail-header {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
  padding-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
}

.detail-cover {
  width: 200px;
  flex-shrink: 0;
}

.detail-cover img {
  width: 100%;
  height: 280px;
  object-fit: cover;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.detail-basic-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 10px 0;
  line-height: 1.4;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  line-height: 1.6;
}

.info-label {
  color: #909399;
  min-width: 80px;
}

.info-value {
  color: #606266;
  flex: 1;
}

.price-item {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.price-value {
  font-size: 28px;
  font-weight: 600;
  color: #f56c6c;
}

.detail-description {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.description-text {
  font-size: 14px;
  color: #606266;
  line-height: 1.8;
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
}

/* 详情对话框响应式 */
@media (max-width: 768px) {
  .detail-header {
    flex-direction: column;
    align-items: center;
  }

  .detail-cover {
    width: 160px;
  }

  .detail-cover img {
    height: 224px;
  }

  .detail-title {
    font-size: 20px;
  }

  .price-value {
    font-size: 24px;
  }
}
</style>
